﻿using DragonSolution.Web.Common.Common;
using DragonSolution.Web.Data.Entity;
using DragonSolution.Web.Data.Enum;
using DragonSolution.Web.UI.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using static DragonSolution.Web.Common.Common.CommonUtil;

namespace DragonSolution.Web.UI.Areas.AdminMrg.Ashx
{
    /// <summary>
    /// 新闻数据相关操作
    /// </summary>
    public class Mnews : IHttpHandler
    {
        private JavaScriptSerializer json = new JavaScriptSerializer();
        private int type = (int)Subject.新闻;
        private MyDbContext db;

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            context.Response.ContentType = "application/json;charset=utf-8";
            var jsonObj = string.Empty;

            BaseController bc = new BaseController();
            db = bc.GetContext();

            switch (action)
            {
                case "GetCategoryList":
                    jsonObj = GetCategoryList(context);
                    break;
                case "GetSpiltPageCategoryList":
                    jsonObj = GetSpiltPageCategoryList(context);
                    break;
                case "AddNewsType":
                    jsonObj = AddNewsType(context);
                    break;
                case "EditNewsType":
                    jsonObj = EditNewsType(context);
                    break;
                case "DeleteNewsType":
                    jsonObj = DeleteNewsType(context);
                    break;
                case "GetSpiltPageNewsList":
                    jsonObj = GetSpiltPageNewsList(context);
                    break;
                case "DeleteNews":
                    jsonObj = DeleteNews(context);
                    break;
            }

            context.Response.Write(jsonObj);
        }

        /// <summary>
        /// 获取新闻类型列表，构建树形菜单
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetCategoryList(HttpContext context)
        {
            try
            {
                var categoryList = db.Category.Where(x => x.SubjectID == type && x.IsDelete == 0).ToList();
                //添加类型的最终父级
                categoryList.Add(new Category() { CategoryID =0, CategoryName = "新闻类型", ParentID=-1, IsDelete=0, SubjectID=type });
                var list = (from c in categoryList
                            select new
                            {
                                id = c.CategoryID,
                                pId = c.ParentID,
                                name = c.CategoryName
                            });
                
                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = list });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 获取新闻类型分页
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSpiltPageCategoryList(HttpContext context) {
            try
            {
                int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);//页所引
                int pageSize = Convert.ToInt32(context.Request["pageSize"]);//页大小
                int parentTypeId = Convert.ToInt32(context.Request["typeId"]);//父类别id
                var list = db.Category.Where(x => x.IsDelete == 0 && x.SubjectID == type && x.ParentID == parentTypeId).OrderBy(x=>x.CreateTime);
                var spl = new SpiltPageList<Category>(list, pageIndex, pageSize);
                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = spl });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 添加新闻类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string AddNewsType(HttpContext context)
        {
            try
            {
                string name = context.Request["name"];
                int parentId = Convert.ToInt32(context.Request["parentId"]);
                Category c = new Category() { CategoryName = name, ParentID = parentId , SubjectID = type , CreateTime =DateTime.Now};
                db.Category.Add(c);
                db.SaveChanges();

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 编辑新闻类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string EditNewsType(HttpContext context)
        {
            try
            {
                string name = context.Request["name"];
                int currentId = Convert.ToInt32(context.Request["currentId"]);
                int parentId = Convert.ToInt32(context.Request["parentId"]);
                Category c = db.Category.Find(currentId);
                if (c != null) {
                    c.CategoryName = name;
                    c.ParentID = parentId;
                    db.SaveChanges();
                }                

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 删除新闻类型(如果有子级，提醒用户先删除子级，这里在前台做了)
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string DeleteNewsType(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["id"]);
                Category c = db.Category.Find(id);
                if (c != null)
                {
                    //db.Category.Remove(c);
                    //逻辑删除
                    c.IsDelete = 1;
                    db.SaveChanges();
                }                

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSpiltPageNewsList(HttpContext context)
        {
            try
            {
                int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);//页所引
                int pageSize = Convert.ToInt32(context.Request["pageSize"]);//页大小
                int typeId = Convert.ToInt32(context.Request["typeId"]);//类别id
                string queryName = context.Request["queryName"];
                string queryStartTime = context.Request["queryStartTime"];
                string queryEndTime = context.Request["queryEndTime"];

                var list = db.NewsInfo.Where(x => x.IsDelete == 0);
                if (typeId > 0) {
                    list = list.Where(x => x.NewsCategory == typeId);
                }
                if (!string.IsNullOrEmpty(queryName)) {
                    list = list.Where(x => x.NewsName.Contains(queryName));
                }
                if (!string.IsNullOrEmpty(queryStartTime))
                {
                    DateTime startTime = Convert.ToDateTime(queryStartTime);
                    list = list.Where(x => x.NewsPostTime>= startTime);
                }
                if (!string.IsNullOrEmpty(queryEndTime))
                {
                    DateTime endTime = Convert.ToDateTime(queryEndTime).AddDays(1);
                    list = list.Where(x => x.NewsPostTime < endTime);
                }
                //排序
                list = list.OrderByDescending(x => x.IsTop).ThenByDescending(x=>x.NewsPostTime);

                var spl = new SpiltPageList<NewsInfo>(list, pageIndex, pageSize);
                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = spl });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string DeleteNews(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["id"]);
                NewsInfo news = db.NewsInfo.Find(id);
                if (news != null)
                {
                    //逻辑删除
                    news.IsDelete = 1;
                    db.SaveChanges();
                    //删除文章中可能有的图片
                    //这里逻辑删除，不删除图片
                    //StringUtil.DelectHtmlImgList(news.NewsContent); 
                }

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}